package com.etoak.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO uploadImage(MultipartFile pic) {
        if (ObjUtil.isEmpty(pic) || pic.isEmpty()) {
            throw new CustomException("文件不允许是空");
        }
        String contentType = pic.getContentType();
        if (!imageProperties.getTypeList().contains(contentType)) {
            String types = imageProperties.getTypeList().stream()
                    .map(x -> x.split("/")[1])
                    .collect(Collectors.joining(","));
            throw new CustomException("仅允许" + types + "类型的文件");
        }
        String location = imageProperties.getLocation();
        File parent = new File(location);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        String originalFilename = pic.getOriginalFilename();
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(originalFilename);
        File target = new File(parent, fileName);
        try {
            pic.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String result = imageProperties.getPrefix().endsWith(StrUtil.SLASH) ? imageProperties.getPrefix() + fileName
                : imageProperties.getPrefix() + StrUtil.SLASH + fileName;
        return ResultVO.success(result);
    }
}
